<!-- src/components/BaseInput.vue -->
<template>
  <div class="base-input" :class="{ 'has-error': error }">
    <!-- 左侧图标（可选） -->
    <span v-if="icon" class="input-icon">{{ icon }}</span>

    <!-- 输入框 -->
    <input
      :type="showPassword ? 'text' : type"
      :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"
      :placeholder="placeholder"
      class="input-field"
      :class="{ 'with-icon': icon }"
    />

    <!-- 密码可见切换（仅当 type='password' 时显示） -->
    <button
      v-if="type === 'password'"
      type="button"
      @click="togglePassword"
      class="password-toggle"
    >
      {{ showPassword ? '🙈' : '👁️' }}
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 定义 props
const props = defineProps({
  modelValue: {
    // 必须叫 modelValue 才能支持 v-model
    type: [String, Number],
    default: '',
  },
  type: {
    type: String,
    default: 'text',
  },
  placeholder: {
    type: String,
    default: '',
  },
  icon: {
    type: String,
    default: '',
  },
  error: {
    type: Boolean,
    default: false,
  },
})

// 定义 emits
const emit = defineEmits(['update:modelValue'])

// 密码可见切换
const showPassword = ref(false)
const togglePassword = () => {
  showPassword.value = !showPassword.value
}
</script>

<style scoped>
.base-input {
  position: relative;
  display: inline-block;
  width: 100%;
}

.input-field {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.2s;
}

.input-field.with-icon {
  padding-left: 36px;
}

.base-input.has-error .input-field {
  border-color: #e53e3e;
}

.input-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
  font-weight: bold;
}

.password-toggle {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
}
</style>
